package com.ys.controller.api.outer;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.*;
import com.ys.config.MyConfig;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.util.RedisUtil;
import com.ys.util.RestClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 百度千帆大模型接口****对接逸知道AI
 */
@Controller
@RequestMapping("/api/outer/baiDuEKnowAi")
public class ApiOuterBaiDuEKnowAiController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterBaiDuEKnowAiController.class);

	//获取百度千帆应用appid
	private static String APPID = MyConfig.getEknowAiAppId();
	//获取百度千帆应用apikey
	private static String APIKEY = MyConfig.getEknowAiApiKey();
	//获取百度千帆应用Secret Key
	private static String SECRETKLEY = MyConfig.getEknowAiSecretKey();

	@Autowired
	private RedisUtil redisUtil;

    @Autowired
    private RestClientUtil restClientUtil;

	/**
	 * 获取百度应用的accessToken api
	 * @return 返回accessToken
	 */
	public String getBaiDuAccessToken() {
        //先查redis缓存
        String accessToken = null;
        if(redisUtil.get("baiDuAccessToken"+APPID)!= null && !"".equals(redisUtil.get("baiDuAccessToken"+APPID))){
            accessToken = redisUtil.get("baiDuAccessToken"+APPID) ;
            //logger.info("【百度千帆】", "Redis获取access_token="+accessToken);
        }else {
            try {
                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body = RequestBody.create(mediaType, "");
                Request request = new Request.Builder()
                        .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + APIKEY + "&client_secret=" + SECRETKLEY + "&grant_type=client_credentials")
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Accept", "application/json")
                        .build();
                Response response = client.newCall(request).execute();
                JSONObject apiResult =JSONObject.parseObject(response.body().string());
                logger.info("【百度千帆】获取百度应用的accessToken api返回："+apiResult);
                if(apiResult.get("error")!=null && !"".equals(apiResult.get("error").toString())){
                    accessToken = null ;
                    logger.error("!!!!!百度千帆!!!!!", "获取access_token失败，error：{"+apiResult.get("error").toString()+"}，error_description：", apiResult.get("error_description").toString());
                }else {
                    int expiresIn = (int) apiResult.get("expires_in");
                    accessToken = apiResult.get("access_token").toString();
                    //设置缓存和过期时间expireIn ，百度Access Token的有效期是30天,单位是秒
                    redisUtil.setEx("baiDuAccessToken"+APPID, accessToken, expiresIn, TimeUnit.SECONDS);
                    //logger.info("【百度千帆】", "API获取access_token="+accessToken);
                }
            }catch (Exception _err){
                logger.error("!!!!!百度千帆!!!!!", _err.getMessage(),_err);
            }
        }
        return accessToken;
	}


    /**
     * ERNIE-Bot-turbo模型对话chat接口，无知识库问答
     * ERNIE-Bot-turbo是百度自行研发的大语言模型，覆盖海量中文数据，具有更强的对话问答、内容创作生成等能力，响应速度更快。
     * sentStr:messages聊天上下文信息，stream是否以流式接口的形式返回数据默认false，temperature默认0.95，top_p默认0.7，penalty_score默认1.0，system模型人设，user_id用户的唯一标识符
     * @return id本轮对话的id，object回包类型，created	时间戳，is_truncated当前生成的结果是否被截断，result对话返回结果，
     *          need_clear_history表示用户输入是否存在安全，ban_round此字段会告知第几轮对话有敏感信息，usage token统计信息
     */
    @PostMapping("/ernieBotTurboChat")
    @ResponseBody
    public  JSONObject ernieBotTurboChat(HttpServletRequest request, HttpServletResponse response, @org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();

        //获取百度千帆accessToken
        String accessToken = getBaiDuAccessToken();
        try {
            //参数格式转换
            //ObjectMapper objectMapper = new ObjectMapper();
            //String sentStr = objectMapper.writeValueAsString(params);
            //url设置
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token="+accessToken;
            result = baiDuAiApiHttpClient(sentStr,url);
            logger.info("【百度千帆】模型对话chat接口，无知识库问答返回："+result);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!百度千帆接口获取失败(ernieBotTurboChatNoKnowLadge)：", e.getMessage(),e);
        }
        return result;
    }


    /**
     * 百度模型对话chat接口
     */
    @PostMapping("/baiDuModelChat")
    @ResponseBody
    public  JSONObject baiDuModelChat(HttpServletRequest request, HttpServletResponse response, @org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();

        //获取百度千帆accessToken
        String accessToken = getBaiDuAccessToken();
        try {
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map = objectMapper.readValue(sentStr, HashMap.class);
            String pathSuffix = map.get("pathSuffix");//ai模型接口后缀
            //url设置
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/"+pathSuffix+"?access_token="+accessToken;
            result = baiDuAiApiHttpClient(sentStr,url);
            logger.info("【百度千帆】百度Ai模型后缀："+pathSuffix+" 对话chat接口，无知识库问答返回："+result);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!百度千帆接口获取失败(baiDuModelChat)：", e.getMessage(),e);
        }
        return result;
    }



    /**
     * ERNIE-Bot-turbo模型对话chat接口，带知识库问答
     * ERNIE-Bot-turbo是百度自行研发的大语言模型，覆盖海量中文数据，具有更强的对话问答、内容创作生成等能力，响应速度更快。
     * @param request
     * @param response
     * @param sentStr
     * @return
     */
    @PostMapping("/ernieBotTurboChatWithKnowLadge")
    @ResponseBody
    public JSONObject ernieBotTurboChatWithKnowLadge(HttpServletRequest request, HttpServletResponse response,
                                                     @org.springframework.web.bind.annotation.RequestBody String sentStr

    ){
        JSONObject result = new JSONObject();
        try {
            //获取百度千帆accessToken
            String accessToken = getBaiDuAccessToken();
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map = objectMapper.readValue(sentStr, HashMap.class);
            String pathSuffix = map.get("pathSuffix");//知识库插件后缀

            logger.info("【百度千帆】ERNIE-Bot-turbo模型对话chat接口，发送的参数："+sentStr);
            //url设置
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/plugin/"+pathSuffix+"/?access_token="+accessToken;
            result = baiDuAiApiHttpClient(sentStr,url);
            logger.info("【百度千帆】ERNIE-Bot-turbo模型对话chat接口，带知识库问答返回："+result);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!百度千帆接口获取失败(ernieBotTurboChatWithKnowLadge)：", e.getMessage(),e);
        }
        return result;
    }

    //Embedding-V1模型向量化接口
    public JSONObject getEmbeddingsByEmbeddingV1(Map<String,Object> params){
        JSONObject result = new JSONObject();
        try {
            //获取百度千帆accessToken
            String accessToken = getBaiDuAccessToken();

            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            String sentStr = objectMapper.writeValueAsString(params);

            logger.info("【百度千帆】Embedding-V1模型向量化接口，发送的参数："+sentStr);
            //url设置
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings/embedding-v1?access_token="+accessToken;
            result = baiDuAiApiHttpClient(sentStr,url);
            logger.info("【百度千帆】Embedding-V1模型向量化接口，返回："+result);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!百度千帆接口获取失败(getEmbeddingsByEmbeddingV1)：", e.getMessage(),e);
        }
        return result;
    }


    //bge_large_zh模型向量化接口
    public JSONObject getEmbeddingsByBgeLargeZh(Map<String,Object> params){
        JSONObject result = new JSONObject();
        try {
            //获取百度千帆accessToken
            String accessToken = getBaiDuAccessToken();

            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            String sentStr = objectMapper.writeValueAsString(params);

            logger.info("【百度千帆】bge_large_zh模型向量化接口，发送的参数："+sentStr);
            //url设置
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings/bge_large_zh?access_token="+accessToken;
            result = baiDuAiApiHttpClient(sentStr,url);
            logger.info("【百度千帆】bge_large_zh模型向量化接口，返回："+result);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!百度千帆接口获取失败(getEmbeddingsByBgeLargeZh)：", e.getMessage(),e);
        }
        return result;
    }


    /**
     * 新建知识库接口
     * 返回向量数据库索引名称
     */
    @PostMapping("/addKnowledgeBase")
    @ResponseBody
    public JSONObject addKnowledgeBase(HttpServletRequest request, HttpServletResponse response){
        JSONObject result = new JSONObject();
        try {
            String indexName = restClientUtil.putIndex();
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            result.put("indexName", indexName);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!新建知识库失败(addKnowledgeBase)：", e.getMessage(),e);
        }
        return result;
    }



    /**
     * 删除知识库接口
     * 返回向量数据库索引名称
     */
    @PostMapping("/delKnowledgeBase")
    @ResponseBody
    public JSONObject delKnowledgeBase(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map = objectMapper.readValue(sentStr, HashMap.class);
            String indexName = map.get("indexName");//知识库索引名称
            String backIndexName = restClientUtil.deletelIndex(indexName);
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            result.put("indexName", backIndexName);
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!删除知识库失败(delKnowledgeBase)：", e.getMessage(),e);
        }
        return result;
    }


    /**
     * 新增知识库向量数据接口
     * 成功返回向量数据id
     */
    @PostMapping("/addKnowledgeList")
    @ResponseBody
    public JSONObject addKnowledgeList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("新增知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);
            List<String> inputList = (List<String>)map.get("information");//内容
            String indexName = map.get("indexName").toString();//索引名称
            //向量化接口入参
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            List<String> shardIdList = new ArrayList<>();
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");
                if(data!=null && data.size()>0){
                    for(JSONObject item : data){
                        List<Double> embedding = (List<Double>)item.get("embedding");//返回的向量内容
                        String shardId = restClientUtil.putVectorByIndex(indexName,embedding);
                        shardIdList.add(shardId);
                    }
                }
                if(shardIdList!=null && shardIdList.size()>0){
                    result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                    result.put("shardId", shardIdList);
                }else {
                    result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!新增知识库向量数据出错(addKnowledgeList)：", e.getMessage(),e);
        }
        return result;
    }




    /**
     * 批量新增知识库向量数据接口
     * 成功返回向量数据id
     */
    @PostMapping("/addKnowledgeListByList")
    @ResponseBody
    public JSONObject addKnowledgeListByList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("批量新增知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);
            List<String> inputList = (List<String>)map.get("information");//内容
            String indexName = map.get("indexName").toString();//索引名称
            //向量化接口入参
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            List<String> shardIdList = new ArrayList<>();
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");
                if(data!=null && data.size()>0){
                    shardIdList = restClientUtil.putVectorByIndexByList(indexName,data);
                }
                if(shardIdList!=null){
                    result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                    result.put("shardIdList", shardIdList);
                }else {
                    result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!批量新增知识库向量数据出错(addKnowledgeListByList)：", e.getMessage(),e);
        }
        return result;
    }



    /**
     * 批量新增知识库向量数据接口,外加参数
     * 成功返回向量数据id
     */
    @PostMapping("/putVectorWithDataByList")
    @ResponseBody
    public JSONObject putVectorWithDataByList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("批量新增知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);
            List<String> inputList = (List<String>)map.get("information");//内容
            String indexName = map.get("indexName").toString();//索引名称
            String shardId = map.get("shardId").toString();//分块id
            String knowledgeId = map.get("knowledgeId").toString();//其他参数
            //向量化接口入参
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            List<String> shardIdList = new ArrayList<>();
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");
                if(data!=null && data.size()>0){
                    shardIdList = restClientUtil.putVectorWithDataByList(indexName,data,shardId,knowledgeId);
                }
                if(shardIdList!=null){
                    result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                    result.put("shardIdList", shardIdList);
                }else {
                    result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!批量新增知识库向量数据出错(addKnowledgeListByList)：", e.getMessage(),e);
        }
        return result;
    }


    /**
     * 修改知识库向量数据接口
     * 成功返回向量数据id
     */
    @PostMapping("/updateKnowledgeList")
    @ResponseBody
    public JSONObject updateKnowledgeList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("修改知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);
            List<String> inputList = (List<String>)map.get("information");//内容
            String indexName = map.get("indexName").toString();//索引名称
            String shardId = map.get("shardId").toString();//向量数据id
            //向量化接口入参
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");
                if(data!=null && data.size()>0){
                    for(JSONObject item : data){
                        List<Double> embedding = (List<Double>)item.get("embedding");//返回的向量内容
                        shardId = restClientUtil.updateVectorByIndex(indexName,shardId,embedding,true);
                    }
                }
                if(shardId!=null){
                    result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                    result.put("shardId", shardId);
                }else {
                    result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!修改知识库向量数据出错(updateKnowledgeList)：", e.getMessage(),e);
        }
        return result;
    }



    /**
     * 删除知识库向量数据接口
     * 成功返回向量数据id
     */
    @PostMapping("/delKnowledgeList")
    @ResponseBody
    public JSONObject delKnowledgeList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("删除知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);
            String indexName = map.get("indexName").toString();//索引名称
            String shardId = map.get("shardId").toString();//向量数据id
            shardId = restClientUtil.deleteVectorByIndex(indexName,shardId);
            if(shardId!=null){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                result.put("shardId", shardId);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }

        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!新增知识库向量数据出错(addKnowledgeList)：", e.getMessage(),e);
        }
        return result;
    }

    /**
     * 查询知识库向量数据接口
     * 成功返回向量数据id集合
     */
    @PostMapping("/searchKnowledgeList")
    @ResponseBody
    public JSONObject searchKnowledgeList(HttpServletRequest request, HttpServletResponse response,@org.springframework.web.bind.annotation.RequestBody String sentStr){
        JSONObject result = new JSONObject();
        try {
            logger.info("查询知识库向量数据接口入参："+sentStr);
            //参数格式转换
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(sentStr, HashMap.class);

            List<String> inputList = (List<String>)map.get("information");//内容
            //向量化接口入参
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            List<Map<String,Object>> shardIdList = new ArrayList<>();
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");//embedding信息
                JSONObject usage = (JSONObject) embeddingBack.get("usage");//token统计信息
                int total_tokens = Integer.parseInt(usage.get("total_tokens").toString()) ;//tokens总数
                if(data!=null && data.size()>0){
                    for(JSONObject item : data){
                        List<Double> embedding = (List<Double>)item.get("embedding");//返回的向量内容
                        int size = Integer.parseInt(map.get("size").toString());//返回数量
                        float score = Float.parseFloat(map.get("score").toString());//置信度
                        List<String> indexNameList = (List<String>) map.get("indexNameList");//索引名称
                        shardIdList = restClientUtil.searchVectorByIndex(indexNameList, embedding,size,score);
                    }
                }
                if(shardIdList!=null){
                    result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                    result.put("shardIdList", shardIdList);
                    result.put("totalTokens", total_tokens);
                }else {
                    result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        } catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("!!!!!新增知识库向量数据出错(addKnowledgeList)：", e.getMessage(),e);
        }
        return result;
    }



    /**
     * 百度ai Api访问统一方式
     * @param sentStr 参数
     * @param url 接口路径
     * @return JSONObject
     * @throws IOException
     */
    public JSONObject baiDuAiApiHttpClient(String sentStr,String url) throws IOException {
        //接口参数设置
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, sentStr);
        Request apiRequest = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        //返回参数
        Response apiResponse = client.newCall(apiRequest).execute();
        JSONObject result =JSONObject.parseObject(apiResponse.body().string());
        return result;
    }



    /**
     * 开发用
     */
    @RequestMapping("/test1")
    @ResponseBody
    public void test1(HttpServletRequest request, HttpServletResponse response ){
        try {
            List<String> inputList = new ArrayList<>();
            /*
            inputList.add("逸思电商各职能部门与销售约责如下：\n" +
                    "\t产品设计中心：\n" +
                    "\t\t1、产品：\n" +
                    "\t\t\t产品要求有：\n" +
                    "\t\t\t\t（1）、毛利率：预算空运毛利率大于等于10%。\n" +
                    "\t\t\t\t（2）、建议售价：大于等于£4.59，小于等于£11.99（以0.59或0.99结尾），并要求低于参考链接价格*0.9。\n" +
                    "\t\t\t\t（3）、产品成本：采购价小于等于¥15，且满足（采购价+空运预算）小于等25。\n" +
                    "\t\t\t\t（4）、产品尺寸：产品包装体积需满足：长*宽*高≤1900cm³，长≤33cm，宽≤23cm，高≤12cm。\n" +
                    "\t\t\t\t（5）、子件：产品子件项数≤8个。\n" +
                    "\t\t\t\t（6）、参考卖家信息：上架时间≤540天。\n" +
                    "\t\t\t\t（7）、精品不做特殊要求、以产品发布时公布参数为准。");

             */
            //inputList.add("如果不满足产品要求：\n" +
            //"\t\t\t\t（1）、更换一款公司优品（到仓库30天内提出货值赔偿）。");
            inputList.add("产品的建议售价是？");
            Map<String,Object> params = new HashMap<>();
            params.put("input",inputList);
            //params.put("user_id","");
            JSONObject embeddingBack = getEmbeddingsByEmbeddingV1(params);
            //getEmbeddingsByBgeLargeZh(params);
            if(embeddingBack.get("error_code")==null){
                List<JSONObject> data = (List<JSONObject>)embeddingBack.get("data");
                if(data!=null && data.size()>0){
                    for(JSONObject item : data){
                        List<Double> embedding = (List<Double>)item.get("embedding");//返回的向量内容
                        //System.out.println("新增embedding："+embedding);
                        //System.out.println("新增："+restClientUtil.putVectorByIndex("eknow_index_1187080052005666816",embedding));

                        //System.out.println("查询embedding："+embedding);
                        //System.out.println("查询："+restClientUtil.searchVectorByIndex(Arrays.asList("eknow_index_1187080052005666816"),embedding,10));

                        //System.out.println("修改embedding："+embedding);
                        //System.out.println("修改："+restClientUtil.updateVectorByIndex("eknow_index_1187080052005666816","eknow_shard_1187083202859106304",embedding,false));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 开发用
     */
    @RequestMapping("/test2")
    @ResponseBody
    public void test2(HttpServletRequest request, HttpServletResponse response ){
        try {
            //System.out.println("新增索引："+restClientUtil.putIndex());
            //System.out.println("删除数据："+restClientUtil.deleteVectorByIndex("eknow_index_1187080052005666816","eknow_shard_1187083202859106304"));
            System.out.println("删除索引："+restClientUtil.deletelIndex("eknow_index_1187080052005666816"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
